package com.xiaolanshu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaolanshu.entity.NoteComment;
import com.xiaolanshu.entity.User;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.mapper.NoteCommentMapper;
import com.xiaolanshu.mapper.UserMapper;
import com.xiaolanshu.service.NoteCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class NoteCommentServiceImpl implements NoteCommentService {

    @Autowired
    private NoteCommentMapper noteCommentMapper;
    @Autowired
    private UserMapper userMapper;
    //获取评论列表
    @Override
    public List<NoteComment> findCommentListById(Long noteId) {
        //根据笔记id查询
        LambdaQueryWrapper<NoteComment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NoteComment::getNoteId,noteId).eq(NoteComment::getDeleted,0);
        List<NoteComment> noteComments = noteCommentMapper.selectList(lqw);
        //遍历取出评论
        List<NoteComment> comments = new ArrayList<>();
        for (NoteComment n:noteComments
             ) {
            //根据评论用户内容获取用户昵称
            LambdaQueryWrapper<User> lqw2 = new LambdaQueryWrapper<>();
            //构造查询条件，根据用户id查询且仅查询用户名和用户头像
            lqw2.select(User::getUsername,User::getHeadphoto).eq(User::getId,n.getUserId());
            User user = userMapper.selectOne(lqw2);

            //创建一个NoteComment对象，保存评论内容和评论的用户id和评论时间
            NoteComment noteComment = new NoteComment();
            noteComment.setComment(n.getComment());
            noteComment.setCreated(n.getCreated());
            noteComment.setUsername(user.getUsername());
            noteComment.setHeadphoto(user.getHeadphoto());

            comments.add(noteComment);

        }
        return comments;
    }
    //保存评论信息
    @Override
    public int saveComment(Long noteId, String comment) {
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();
        //保存评论信息到数据库
        NoteComment noteComment = new NoteComment();
        noteComment.setUserId(userId);
        noteComment.setNoteId(noteId);
        noteComment.setComment(comment);
        return noteCommentMapper.insert(noteComment);

    }
}
